package com.android.myapplication;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.DownloadListener;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import com.android.myapplication.event.Event_ChangeUrl;
import com.android.myapplication.util.AnimUtil;
import com.android.myapplication.util.GlideEngine;
import com.android.myapplication.util.SPUtil;
import com.bumptech.glide.Glide;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends FragmentActivity {

    WebView webview;    //内置浏览器控件
    TextView tv_title;   //标题控件
    TextView tv_set;
    ImageView iv_back;
    RelativeLayout rl_cover;   //覆盖在上面的启动界面
    RelativeLayout rl_loading;   //覆盖在上面的Loading界面
    ImageView iv_bg;

    Handler handler = new Handler();
    ValueCallback<Uri[]> uploadMessageAboveL;   //H5选择图片事件回调
    String host_url = "file:///android_asset/test.html";      //网页地址
    Context mContext;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        CookieManager.getInstance().removeAllCookie();   //清楚全部缓存
        setContentView(R.layout.activity_main);
        initView();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //初始化控件
    private void initView() {
        webview = findViewById(R.id.webview);
        tv_title = findViewById(R.id.tv_title);
        tv_set = findViewById(R.id.tv_set);
        iv_back = findViewById(R.id.iv_back);
        rl_cover = findViewById(R.id.rl_cover);
        rl_loading = findViewById(R.id.rl_loading);
        iv_bg = findViewById(R.id.iv_bg);

        Glide.with(this)
                .load(getDrawable(R.drawable.img_bg))
                .into(iv_bg);

        handler.postDelayed(runnable_dismiss,5000);    //延迟两秒后 遮盖层 消失

        tv_set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(mContext, SettingActivity.class));
            }
        });
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webview.goBack();
            }
        });


        configWebview();

        //从设置获取url
//        host_url = SPUtil.getStringValue(mContext, "HOST", "file:///android_asset/test.html");
        webview.loadUrl(host_url);
    }

    Runnable runnable_dismiss=new Runnable() {
        @Override
        public void run() {
            AnimUtil.fadeOut(rl_cover);
        }
    };

    //配置webview参数
    private void configWebview() {
        WebSettings mWebSettings = webview.getSettings();
        mWebSettings.setJavaScriptEnabled(true);
        mWebSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);  //提高渲染的优先级
//        mWebSettings.setBlockNetworkImage(true);
        mWebSettings.setJavaScriptEnabled(true);                    //  支持Javascript 与js交互
        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);//  支持通过JS打开新窗口
        mWebSettings.setAllowFileAccess(true);                      //  设置可以访问文件
        mWebSettings.setSupportZoom(true);                          //  支持缩放
        mWebSettings.setBuiltInZoomControls(true);                  //  设置内置的缩放控件
//        mWebSettings.setUseWideViewPort(true);                      //  自适应屏幕

        mWebSettings.setLoadWithOverviewMode(true);
//
        mWebSettings.setAllowContentAccess(true);
        mWebSettings.setAllowFileAccessFromFileURLs(true);
//        mWebSettings.setAllowUniversalAccessFromFileURLs(true);
//        mWebSettings.setDatabaseEnabled(true);
//
//        //自适应屏幕
        mWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
////
////        mWebSettings.setSupportMultipleWindows(false);               //  多窗口
        mWebSettings.setDefaultTextEncodingName("utf-8");           //  设置编码格式
        mWebSettings.setAppCacheEnabled(false);
        mWebSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);       //  缓存模式

        mWebSettings.setDomStorageEnabled(true);  // 开启 localStorage
        //设置不用系统浏览器打开,直接显示在当前WebView
        webview.setWebChromeClient(new MyWebClient());
        //设置不用系统浏览器打开,直接显示在当前WebView
        webview.setWebViewClient(new WebViewClient() {

            private String startUrl;

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                Log.i("test", "onPageStarted");
                startUrl = url;
                Log.i("test", "startUrl:" + startUrl);

                if (url.endsWith(".pdf")) {
                    iv_back.setVisibility(View.VISIBLE);
                } else {
                    iv_back.setVisibility(View.GONE);
                }
            }

            //url加载完成
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                Log.i("test", "onPageFinished");
                if (url.endsWith(".pdf")) {
                    iv_back.setVisibility(View.VISIBLE);
                } else {
                    iv_back.setVisibility(View.GONE);
                }
                //隐藏Loading
                rl_loading.setVisibility(View.GONE);
                //隐藏遮罩层
                AnimUtil.fadeOut(rl_cover);
                handler.removeCallbacks(runnable_dismiss);  //清理掉计时器
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                //在这里加判断
//                if(url.contains("facebook.com") || url.contains("youtube.com") || url.contains("vm.th") || url.contains(".pdf")){        //第三方的时候跳出浏览器
//                    Intent intent = new Intent();
//                    intent.setAction(Intent.ACTION_VIEW);
//                    intent.setData(Uri.parse(url));
//                    mContext.startActivity(intent);
//                    return true;
//                }
                Log.i("test", "shouldOverrideUrlLoading:" + url);

                if (startUrl != null && startUrl.equals(url)) {
                    view.loadUrl(url);
                } else {
                    //交给系统处理
                    return super.shouldOverrideUrlLoading(view, url);
                }
                return true;
            }

        });

        // 设置下载监听
        webview.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                //有文件下载，跳系统浏览器
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
            }
        });
    }

    //自定义浏览器事件
    class MyWebClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            tv_title.setText(title);
        }

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> valueCallback, FileChooserParams fileChooserParams) {
            uploadMessageAboveL = valueCallback;
            openImageChooserActivity();
            return true;
        }

    }


    //打开相册，并回调给H5
    private void openImageChooserActivity() {
        String[] permissions = new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        //是否永久拒绝了权限
        boolean isPermanentDenied = XXPermissions.isPermanentDenied((Activity) mContext, permissions);
        Log.i("test", "isPermanentDenied:" + isPermanentDenied);
        XXPermissions.with(mContext).permission(permissions).request(new OnPermissionCallback() {
            @Override
            public void onGranted(List<String> permissions, boolean all) {
                //权限允许
                PictureSelector.create(mContext)
                        .openGallery(SelectMimeType.ofImage())
                        .setImageEngine(GlideEngine.createGlideEngine())
//                        .setMaxSelectNum(1)  //一次最多选几张图
                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                            @Override
                            public void onResult(ArrayList<LocalMedia> result1) {
                                List<String> list = new ArrayList<>();
                                handler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        List<Uri> uriList = new ArrayList<>();
                                        for (LocalMedia media : result1) {
                                            Uri uri = Uri.parse("file://" + media.getRealPath());
                                            uriList.add(uri);
                                            Log.i("test", "uri.getPath():" + uri.toString());
                                        }
                                        uploadMessageAboveL.onReceiveValue(uriList.toArray(new Uri[list.size()]));   //回调给H5数据
                                    }
                                }, 200);
                            }

                            @Override
                            public void onCancel() {
                                uploadMessageAboveL.onReceiveValue(new Uri[]{});   //回调给H5数据，未选择图片也要回调，不然input标签不会再次触发
                            }
                        });
            }

            @Override
            public void onDenied(List<String> permissions, boolean never) {
                //权限被拒绝
                if (never) {
                    if (isPermanentDenied)  //永久拒绝了，只能跳系统设置页打开
                    {
                        XXPermissions.startPermissionActivity(mContext, permissions);
                        Toast.makeText(mContext, "您已经拒绝了相册权限，需要在系统设置中将权限打开后重试", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(mContext, "您拒绝了相册权限，无法使用相册功能", Toast.LENGTH_LONG).show();
                }
                uploadMessageAboveL.onReceiveValue(new Uri[]{});
            }
        });
    }


    //监听事件，设置页 改变了URL
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Event_ChangeUrl event) {
        CookieManager.getInstance().removeAllCookie();   //清除全部缓存
        host_url = SPUtil.getStringValue(mContext, "HOST", "");
        webview.loadUrl(host_url);
    }

    @Override
    public void onBackPressed() {
        if (!webview.getUrl().equals(host_url)) {
            webview.goBack();
        } else {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(mContext, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                super.onBackPressed();
            }
        }
    }

    private long exitTime = 0;
}